package com.longai.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import util.Page;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.longai.model.Newslike;
import com.longai.model.User;
import com.longai.service.NewsService;
import com.longai.service.NewslikeService;
import com.longai.service.UserService;
import com.longai.vo.NewsLikeVo;

@Controller
@RequestMapping("newslike")
public class NewslikeAction {
    @Autowired
	NewslikeService newslikeservice;
	@Autowired
	UserService userService;
	@Autowired
	NewsService newsService;
	@RequestMapping(value="likesByNewsId",method = RequestMethod.GET)
	@ResponseBody//根据newsId返回鸡汤赞
	public Object likeByNewsId(@RequestParam("newsId") String newsid,
			@RequestParam("currentPage") String currentPage,
			@RequestParam("amount") String amount){
		Page u=newslikeservice.findByNewId(newsid,currentPage,amount);
		List<Newslike> s=u.getList();
		List<NewsLikeVo> g=new ArrayList();
		if(!s.isEmpty()){
			for(Newslike q:s){
				NewsLikeVo vo=new NewsLikeVo();
				vo.setNewsId(q.getNews().getNewsId());
				vo.setNewsLikeId(q.getNewslikeId());
			    vo.setPubtime(q.getNewslikePubtime());
				vo.setNickname(q.getUser().getNickname());
				vo.setUserId(q.getUser().getUserId());
				g.add(vo);
			}
			u.setList(g);
			return u;
		}
		Newslike gg=new Newslike();
		return gg;
	}
	@RequestMapping(value="newsLike",method=RequestMethod.GET)//根据app的实体保存点赞
	@ResponseBody
	public Object newsLike(@RequestParam(value="newsLike") String newsLike){
		Newslike k=new Newslike();
		try {
			Gson gson=new Gson();
			NewsLikeVo u=gson.fromJson(newsLike, NewsLikeVo.class);
			User user=userService.findById(u.getUserId());
			Newslike g=new Newslike();
			g.setNewslikeId(u.getNewsLikeId());
			g.setNewslikePubtime(u.getPubtime());
			g.setUser(user);
			g.setNews(newsService.findById(u.getNewsId()));
			newslikeservice.save(g);
			u.setNickname(user.getNickname());
			u.setNewsLikeId(g.getNewslikeId());
			return u;
		} catch (Exception e) {
			// TODO: handle exception
			return k;
		}
	}
	@RequestMapping("deleteNewsLike")
	@ResponseBody
	public int deleteNewsLike(@RequestParam("newsLikeId")String id){
		try {
			Newslike s=newslikeservice.findById(Integer.valueOf(id));
			newslikeservice.delete(s);
			return Integer.valueOf(id);
		} catch (Exception e) {
			// TODO: handle exception
			return 0;
		}
	}
}
